﻿using System;

using Gonte.Reflection;

namespace Gonte.Wpf.Controls.ViewModel
{
    public class FolderViewModel
        : ContentViewModel
    {
        #region Constructors

        public FolderViewModel(ContentViewModelInfo viewModelInfo, string childrenPropertyName, ContentViewModel parent, object model)
            : base(viewModelInfo, parent, model)
        {
            _childrenPropertyName = childrenPropertyName;
        } 

        #endregion

        #region Overridables

        public override void LoadChildren()
        {
            Children.Clear();

            // Call the data filler callback
            if (null != LoadData)
            {
                LoadData(_model); // Needed to make sure that the children are added to the parent
            }

            // Get the child or children from the parent
            TypeAccessor typeAccessor = TypeAccessor.GetTypeAccessor(_model.GetType());
            object child = typeAccessor.GetValue(_model, _childrenPropertyName);

            // Populate the children view models
            Type type = CollectionHelper.GetItemType(child.GetType());
            ItemViewModelInfo childViewModelInfo = ItemObjectViewModelInfo.GetInfo(type);

            ContentObjectViewModel parent = (ContentObjectViewModel)_parent;
            parent.CreateChildren(this, childViewModelInfo, child);

            base.LoadChildren(); // Handle the sort
        } 

        #endregion

        #region Properties

        public string ChildrenPropertyName
        {
            get { return _childrenPropertyName; }
        } 

        #endregion

        #region Load the children data event handlers

        public delegate void LoadDataHandler(object model);

        public LoadDataHandler LoadData; 

        #endregion

        #region Fields

        private readonly string _childrenPropertyName; 

        #endregion
    }
}
